package com.yft.entity.base;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

public class PagerImpl implements Pager {

	/**
	 * @preserve
	 */
	private int pageSize;

	/**
	 * @preserve
	 */
	private int pageCount;

	/**
	 * @preserve
	 */
	private int recordCount;

	/**
	 * @preserve
	 */
	private int page;

	/**
	 * @preserve
	 */
	private HashMap<String, String> filter = new HashMap<String, String>();

	/**
	 * @preserve
	 */
	private String queryString;

	public PagerImpl() {

	}

	@SuppressWarnings("unchecked")
	public PagerImpl(HttpServletRequest request) throws Exception {
		String encoding = request.getCharacterEncoding();
		this.page = NumberUtils.toInt(request.getParameter("page"));
		this.pageSize = NumberUtils.toInt(request.getParameter("pageSize"));

		String queryString = "";
		Map<String, String[]> parm = request.getParameterMap();
		for (String key : parm.keySet()) {
            String[] val = parm.get(key);
			if (val != null) {
				String value = StringUtils.trimToEmpty(val[0]);
				String value_decode = URLDecoder.decode(value, encoding);
				String value_encode = URLEncoder.encode(value, encoding);
				//String value = StringUtils.trimToEmpty(v[0]);

				filter.put(key, value_decode);
				queryString += key + "=" + value_encode + "&";

			}
		}

		this.queryString = StringUtils.substringBeforeLast(queryString, "&");

	}

	public PagerImpl(int page, int pageSize) {
		this.page = page;
		this.pageSize = pageSize;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize < 1 ? 0 : pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getRecordCount() {
		return recordCount;
	}

	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
		if (pageSize < 1)
			pageCount = 1;
		else
			pageCount = recordCount % pageSize == 0 ? (recordCount / pageSize) : (recordCount / pageSize + 1);
	}

	public int getPage() {
		return page < 1 ? 1 : page;
	}

	public void setPage(int page) {
		this.page = page < 1 ? 1 : page;
	}

	public HashMap<String, String> getFilter() {
		return this.filter;
	}

	public String getQueryString() {
		return this.queryString;
	}

	// -------------------------------------------------------------------- private methods

}